import { message } from 'ant-design-vue';

export function useUpload() {
  // 判断是否是字母
  function isLetter(str: string): boolean {
    return /^[A-Z]+$/i.test(str);
  }
  // 判断表头字段
  function areArraysEqualIgnoreOrder(arr1: any[], arr2: any[]): boolean {
    const sortedArr1 = [...arr1].sort();
    const sortedArr2 = [...arr2].sort();
    if (sortedArr1.length !== sortedArr2.length) {
      return false;
    }
    for (let i = 0; i < sortedArr1.length; i++) {
      if (sortedArr1[i] !== sortedArr2[i]) {
        return false;
      }
    }
    return true;
  }
  // 检查文件扩展名是否为Excel
  function checkIfExcel(fileName: string): boolean {
    const excelExtensions = ['xls', 'xlsx'];
    const fileExtension = fileName.toLowerCase().split('.').pop() || '';
    return excelExtensions.includes(fileExtension);
  }
  const checkExamHeader = (worksheet: any, headers: any) => {
    worksheet?.getRow(1).eachCell((cell: { value: any }) => {
      if (useUpload().isLetter(cell.value)) {
        headers.push(cell.value.toLowerCase());
      }
      else {
        headers.push(cell.value);
      }
    });
    const title = [
      '考试等级',
      '考试日期',
      '报名开始日期',
      '报名截至日期',
      '考情描述',
    ];
    // 拦截错误的表格
    if (!useUpload().areArraysEqualIgnoreOrder(title, headers)) {
      message.error('excel内表格的字段数或表头出错,上传失败！');
      return false;
    }
    return true;
  };
  const checkDetailsHeader = (worksheet: any, headers: any) => {
    worksheet?.getRow(1).eachCell((cell: { value: any }) => {
      if (useUpload().isLetter(cell.value)) {
        headers.push(cell.value.toLowerCase());
      }
      else {
        headers.push(cell.value);
      }
    });
    const title = [
      '单位',
      '人员编码',
      '姓名',
      '是否研发人员（人才云）',
      '是否研发人员（基准岗位）',
      '是否通过研发通用认证',
      '研发通用认证级别',
      '是否通过研发专业认证',
      '研发专业认证级别',
      '研发经验级别',
    ];
    // 拦截错误的表格
    if (!useUpload().areArraysEqualIgnoreOrder(title, headers)) {
      message.error('excel内表格的字段数或表头出错,上传失败！');
      return false;
    }
    return true;
  };
  const checkWorkingHoursHeader = (worksheet: any, headers: any) => {
    worksheet?.getRow(1).eachCell((cell: { value: any }) => {
      if (useUpload().isLetter(cell.value)) {
        headers.push(cell.value.toLowerCase());
      }
      else {
        headers.push(cell.value);
      }
    });
    const title = [
      '工时月份',
      '成员姓名',
      '成员ID',
      '复核工时（天）',
    ];
    // 拦截错误的表格
    if (!useUpload().areArraysEqualIgnoreOrder(title, headers)) {
      message.error('excel内表格的字段数或表头出错,上传失败！');
      return false;
    }
    return true;
  };
  return {
    checkExamHeader,
    isLetter,
    areArraysEqualIgnoreOrder,
    checkIfExcel,
    checkDetailsHeader,
    checkWorkingHoursHeader,
  };
}
